package com.atguigu.bigdata.edu.realtime.app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bigdata.edu.realtime.app.BaseAppV1;
import com.atguigu.bigdata.edu.realtime.common.Constant;
import com.atguigu.bigdata.edu.realtime.util.AtguiguUtil;
import com.atguigu.bigdata.edu.realtime.util.AtguiguUtil;
import com.atguigu.bigdata.edu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.HashMap;

public class Dwd_01_BaseLogApp extends BaseAppV1 {

    private final String START = "start";
    private final String DISPLAY = "display";
    private final String ACTION = "action";
    private final String ERR = "err";
    private final String PAGE = "page";
    private final String VIDEO = "video";
    private final String COMMON = "common";

    public static void main(String[] args) {
        new Dwd_01_BaseLogApp().init(2111,
                2,
                "Dwd_01_BaseLogApp",
                Constant.TOPIC_ODS_LOG);
    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. etl
        SingleOutputStreamOperator<JSONObject> etledStream = etl(stream);
        // 2. 纠正新来客户
        SingleOutputStreamOperator<JSONObject> validatedStream = validateNewOrOld(etledStream);
        // 3. 分流: 手工分流的方式, 侧输出流
        HashMap<String, DataStream<JSONObject>> streams = splitStream(validatedStream);
        // 4. 不同的流的数据写出到不同的 topic 中
        write2Kafka(streams);
    }

    private void write2Kafka(HashMap<String, DataStream<JSONObject>> streams) {
        streams.get(START).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_START));
        streams.get(ERR).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ERR));
        streams.get(ACTION).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ACTION));
        streams.get(DISPLAY).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_DISPLAY));
        streams.get(PAGE).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_PAGE));
        streams.get(VIDEO).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_VIDEO_PLAY));
        streams.get(COMMON).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_COMMON));
    }

    private HashMap<String, DataStream<JSONObject>> splitStream(SingleOutputStreamOperator<JSONObject> validatedStream) {
        /*
         5种日志:

            测输出流

            主流: 启动
            测输出流: 日志 曝光 活动 错误

         */
        // 泛型擦除
        OutputTag<JSONObject> displayTag = new OutputTag<JSONObject>("display") {
        };
        OutputTag<JSONObject> actionTag = new OutputTag<JSONObject>("action") {
        };
        OutputTag<JSONObject> errTag = new OutputTag<JSONObject>("err") {
        };
        OutputTag<JSONObject> pageTag = new OutputTag<JSONObject>("page") {
        };
        OutputTag<JSONObject> videoTag = new OutputTag<JSONObject>("video") {
        };
        OutputTag<JSONObject> commonTag = new OutputTag<JSONObject>("common") {
        };

        SingleOutputStreamOperator<JSONObject> startStream = validatedStream
                .process(new ProcessFunction<JSONObject, JSONObject>() {
                    @Override
                    public void processElement(JSONObject obj,
                                               Context ctx,
                                               Collector<JSONObject> out) throws Exception {

                        System.out.println(AtguiguUtil.toDateTime(obj.getLong("ts")));

                        JSONObject common = obj.getJSONObject("common");
                        if (common != null){
                            ctx.output(commonTag, common);
                        }

                    // 1. 找到启动日志
                        JSONObject start = obj.getJSONObject("start");
                        if (start != null) {
                            out.collect(obj);
                        } else {
                            JSONObject page = obj.getJSONObject("page");

                            //2. 曝光
                            JSONArray displays = obj.getJSONArray("displays");
                            if (displays != null) {
                                for (int i = 0; i < displays.size(); i++) {
                                    JSONObject display = displays.getJSONObject(i);
                                    // 把 common 和 ts 也添加到 display 中
                                    display.putAll(common);
                                    display.putAll(page);
                                    display.put("ts", obj.getLong("ts"));
                                    ctx.output(displayTag, display);
                                }
                                obj.remove("displays"); // 把数据中的 displays 删除
                            }
                            // 3. action
                            JSONArray actions = obj.getJSONArray("actions");
                            if (actions != null) {
                                for (int i = 0; i < actions.size(); i++) {
                                    JSONObject action = actions.getJSONObject(i);
                                    // 把 common 和 ts 也添加到 action 中
                                    action.putAll(common);
                                    action.putAll(page);
                                    ctx.output(actionTag, action);
                                }
                                obj.remove("actions"); // 把数据中的 actions 删除
                            }

                            // 4. video
                            JSONObject videoPlay = obj.getJSONObject("appVideo");
                            if (videoPlay != null) {

                                ctx.output(videoTag, obj);
                            }
                            obj.remove("appVideo");

                            // 5. err
                            JSONObject err = obj.getJSONObject("err");
                            if (err != null) {
                                ctx.output(errTag, obj);
                                obj.remove("err");
                            }
                            // 6. page
                            if (page != null) {
                                // 过滤掉page为空的页面 addBy wangy 20221027
                                ctx.output(pageTag, obj);
                            }
                        }


                    }
                });

        HashMap<String, DataStream<JSONObject>> streams = new HashMap<>();
        streams.put(START, startStream);
        streams.put(DISPLAY, startStream.getSideOutput(displayTag));
        streams.put(ACTION, startStream.getSideOutput(actionTag));
        streams.put(ERR, startStream.getSideOutput(errTag));
        streams.put(PAGE, startStream.getSideOutput(pageTag));
        streams.put(VIDEO, startStream.getSideOutput(videoTag));
        streams.put(COMMON, startStream.getSideOutput(commonTag));

        return streams;

    }

    private SingleOutputStreamOperator<JSONObject> validateNewOrOld(
            SingleOutputStreamOperator<JSONObject> etledStream) {
        /*
        新老客户的标记是如何生成的?
            前端埋点数据生成.
         */

        return etledStream
                .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
                .map(new RichMapFunction<JSONObject, JSONObject>() {

                    private ValueState<String> firstVisitDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        firstVisitDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("firstVisitDate", String.class));
                    }

                    @Override
                    public JSONObject map(JSONObject value) throws Exception {

                        String firstVisitDate = firstVisitDateState.value();
                        Long ts = value.getLong("ts");
                        String today = AtguiguUtil.toDate(ts);

                        JSONObject common = value.getJSONObject("common");
                        String isNew = common.getString("is_new");

                        if ("1".equals(isNew)) {
                            if (firstVisitDate == null) {
                                // 是新用户,状态还是 null, 这个用户首日的首次访问.
                                // 把今天的日期存入到状态

                                firstVisitDateState.update(today);
                            } else if (!today.equals(firstVisitDate)) {
                                // 状态不为空, 需要判断今天和首日访问日期是否一样
                                // 如果不一样, 证明今天不是首日访问, 把 1 改成 0
                                common.put("is_new", "0");
                            }
                        } else {
                            // 来的是老用户, 如果状态为 null, 把状态设置为昨天
                            if (firstVisitDate == null) {
                                String yesterday = AtguiguUtil.toDate(ts - 24 * 60 * 60 * 1000);
                                firstVisitDateState.update(yesterday);
                            }
                        }
                        return value;
                    }
                });
    }

    private SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> stream) {
        return stream
                .filter(new FilterFunction<String>() {
                    @Override
                    public boolean filter(String value) throws Exception {
                        try {
                            JSON.parseObject(value);
                        } catch (Exception e) {
                            System.out.println("日志格式有误, 请检测: " + value);
                            return false;
                        }
                        return true;
                    }
                })
                .map(JSON::parseObject);
    }
}

